package cn.gzsxt.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 作用：用于校验登录状态，所有需要管理员用户信息的操作都拦截
 * 如果发现管理员用户信息，在session已经失效，需要跳转到登录页面，重新登录
 * @author ranger
 *
 */
public class LoginStatusInterceptor implements HandlerInterceptor {

	/**
	 * 操作之前判断session是否存在管理员信息
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		try {
			//1.获得会话对象
			HttpSession session = request.getSession();
			//2.判断会话是否有管理员信息
			Object admin = session.getAttribute("admin");
			if (admin!=null) {
				return true;
			}else{
				//跳转回到登录页面，并且提交登录失效
				request.setAttribute("admin_login_msg", "登录会话失效，请重新登录");
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("admin_login_msg", "出现未知异常，登录会话失效，请重新登录，如果不能登录请联系管理员");
		}
		request.getRequestDispatcher("/login.jsp").forward(request, response);
		return false;
		
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
